package rcpexplorer.views;

import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ITreeSelection;
import org.eclipse.jface.viewers.TreePath;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;
import org.osgi.framework.Bundle;

public class OpenBundleActivatorTypeAction implements IObjectActionDelegate {
	
	private String activatorClassName;

	private IWorkbenchPart view;

	public OpenBundleActivatorTypeAction() {
	}
	
	public void setActivePart(IAction action, IWorkbenchPart targetPart) {
		this.view = targetPart;
		
	}

	public void run(IAction action) {
		if (activatorClassName == null) {
			return;
		}

		Utils.openType(view.getSite().getShell(), activatorClassName);
	}

	public void selectionChanged(IAction action, ISelection selection) {
		activatorClassName = null;
		action.setEnabled(false);
		if (selection instanceof ITreeSelection) {
			ITreeSelection treeSelection = (ITreeSelection) selection;
			TreePath[] paths = treeSelection.getPaths();
			if (paths.length > 0) {
				Object lastSegment = paths[0].getLastSegment();
				Bundle bundle = null;
				if (lastSegment instanceof Bundle) {
					bundle = ((Bundle) lastSegment);
				} else if (lastSegment instanceof AsBundleOf) {
					bundle = ((AsBundleOf) lastSegment).bundle;
				} else if (lastSegment instanceof AsBundleDependency) {
					bundle = ((AsBundleDependency) lastSegment).bundle;
				}
				if (bundle != null) {
					String className = (String) bundle.getHeaders().get("Bundle-Activator");
					if (Utils.isJavaTypeName(className)) {
						activatorClassName = className;
						action.setEnabled(true);
					}
				}
			}
		}		
	}

}
